package com.elasticsearch.demo.config;


import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class MyESConfig {

    @Value("${es.addresses}")
    private String addresses;

    @Value("${es.cluster.name}")
    private String clusterName;

    @Bean
    public TransportClient client() throws UnknownHostException {

        Settings settings = Settings.builder().put("cluster.name", clusterName).build();

        TransportClient client = new PreBuiltTransportClient(settings);

        String[] adds = addresses.split(",");
        for (String address:adds) {
            String host = address.substring(0, address.indexOf(":"));
            Integer port = Integer.parseInt(address.substring(address.indexOf(":") + 1));
            TransportAddress node = new TransportAddress(InetAddress.getByName(host), port);
            client.addTransportAddress(node);
        }

        return client;
    }

}
